package ee.maoinvest.frontend.controller.command.enterpriseCommands;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import ee.maoinvest.ErrorMessage;
import ee.maoinvest.backend.model.data.Enterprise;
import ee.maoinvest.backend.services.EnterpriseService;
import ee.maoinvest.backend.services.implementations.EnterpriseServiceImpl;
import ee.maoinvest.frontend.controller.command.Command;
import ee.maoinvest.frontend.controller.formstringdataconverters.enterpriseforms.DeleteEnterpriseFormConverter;
import ee.maoinvest.frontend.controller.requestprocessors.EnterpriseFormsRequestProcessor;

public class DeleteEnterpriseCommand implements Command
{
	private Logger logger = Logger.getLogger(InsertEnterpriseCommand.class);
	private int operationResult = 0;
	private final int OPERATION_SUCCESSFUL = 1;
	private final int OPERATION_UNSUCCESSFUL = 0;
	private final int PROBABLY_A_DATABASE_ERROR = -1;
	
	
	@Override
	public int executeCommand(HttpServletRequest request,
			HttpServletResponse response) 
	{
		try
		{
			EnterpriseFormsRequestProcessor enterpriseFormsRequestProcessor = new EnterpriseFormsRequestProcessor();
			DeleteEnterpriseFormConverter deleteEnterpriseFormConverter = null;
			deleteEnterpriseFormConverter = enterpriseFormsRequestProcessor.fillDeleteEnterpriseFormConverterWithRequestData(request);
			Enterprise enterprise = deleteEnterpriseFormConverter.convertToModelData();
			
			boolean dataIsOKAfterFormatting = deleteEnterpriseFormConverter.getIsDataAfterFormattingOK();
			
			if (dataIsOKAfterFormatting)
			{
				EnterpriseService enterpriseServiceImpl = new EnterpriseServiceImpl();
				int wasDeletionFromDatabaseSuccessful = enterpriseServiceImpl.deleteEnterprise(enterprise.getEnterpriseID());
				
				if (wasDeletionFromDatabaseSuccessful == OPERATION_SUCCESSFUL)
				{
					operationResult = OPERATION_SUCCESSFUL;
				}
				else
				{
					request.setAttribute("deletingEnterpriseFromADatabaseWasUnsuccessful", 
							ErrorMessage.E0013_ERROR_WHILE_TRYING_TO_DELETE_ENTERPRISE_FROM_DATABASE);
					operationResult = OPERATION_UNSUCCESSFUL;
				}
			}
			else
			{
				operationResult = OPERATION_UNSUCCESSFUL;
			}
			
			request.setAttribute("deleteEnterpriseFormConverter", deleteEnterpriseFormConverter);
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			logger.error(e.getMessage());
			return PROBABLY_A_DATABASE_ERROR;
		}
		
		return operationResult;
	}
}
